﻿using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.FormService;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GuoXinDa.ServicePlugin
{
    [Description("计划订单审核的时候，更新对应的销售订单行号"), HotUpdate]
    public class SetPlanFromSalSeq: AbstractOperationServicePlugIn
    {
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            e.FieldKeys.Add("FMaterialId");//物料编码
            e.FieldKeys.Add("FSaleOrderNo");//需求单据编号
            e.FieldKeys.Add("FSaleOrderEntrySeq");//需求单据行号
        }
        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);
            foreach (var obj in e.SelectedRows.Select(s => s.DataEntity))
            {
                if (obj == null) { return; }
                int salSeq = Convert.ToInt32(obj["SaleOrderEntrySeq"]);
                if (salSeq > 0) { return; }
                DynamicObject material = obj["MaterialId"] as DynamicObject;
                int matId = material == null ? 0 : Convert.ToInt32(material["Id"]);
                string salNo = obj["SaleOrderNo"].ToString();
                int planId = Convert.ToInt32(obj["Id"]);
                SetPlanForSalSeq(matId, salNo, planId);
            }
        }
        /// <summary>
        /// 更新合并生成的计划订单的需求单据行号
        /// </summary>
        /// <param name="matId"></param>
        /// <param name="salNo"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void SetPlanForSalSeq(int matId, string salNo, int planId)
        {
            int seq = GetSalSeq(matId, salNo);
            if (seq > 0)
            {
                UpSeq(planId, seq);
            }
        }
        /// <summary>
        /// 后台更新计划订单行号
        /// </summary>
        /// <param name="matId"></param>
        /// <param name="salNo"></param>
        private void UpSeq(int planId, int seq)
        {
            string sql = string.Format($" /*dialect*/ UPDATE T0 SET T0.FSALEORDERENTRYSEQ={seq} FROM T_PLN_PLANORDER_B T0 WHERE T0.FID={planId}");
            DBServiceHelper.Execute(this.Context, sql);
        }
        /// <summary>
        /// 查询销售订单行号
        /// </summary>
        /// <param name="matId"></param>
        /// <param name="salNo"></param>
        /// <returns></returns>
        private int GetSalSeq(int matId, string salNo)
        {
            int salSeq = 0;
            var result = WebApiServiceCall.ExecuteBillQuery(this.Context, QueryParameter("SAL_SaleOrder", "FSaleOrderEntry_FSeq", $"fbillno='{salNo}' and FMaterialId={matId}"));
            if (result.Count > 0)
            {
                salSeq = Convert.ToInt32(result.FirstOrDefault().FirstOrDefault());
            }
            return salSeq;
        }
        private string QueryParameter(string formId, string fieldKeys, string filterString)
        {
            var param = new
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = filterString
            };
            return JsonConvert.SerializeObject(param);
        }
    }
}
